<script setup>
import { ref } from 'vue';
import { Plus ,Upload} from '@element-plus/icons-vue';
import { useUserStore } from '@/stores'
import {userUpdateAvatarService} from '@/api/user'

const userStore=useUserStore()
const imgUrl=ref(userStore.user.user_pic)
const uploadRef=ref()
const onUpdateStore=useUserStore()
const {getUser} = onUpdateStore

// 点击上传头像按钮的时候触发
const onSelectFile=(File)=>{
  console.log(File);
    // imgUrl.value=URL.createObjectURL(File.raw)
    // 转换成base64格式的文件
    const reader=new FileReader()
    reader.readAsDataURL(File.raw)
    reader.onload=()=>{
        imgUrl.value=reader.result
        console.log(imgUrl.value);
    }
}

// 调用接口 上传头像 
const onUpdateAvatar=async()=>{
    const res=await userUpdateAvatarService(imgUrl.value)
    console.log(res);
    ElMessage.success('头像上传成功')
    getUser()
}
</script>
<template>

   <page-container title="上传头像">
    <!-- show-file-list是否显示已上传的文件列表  auto-upload是否自动上传文件 -->
        <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" ref="uploadRef" :on-change="onSelectFile">
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>

        <br>
        <!-- 按钮 我点击选择图片相当于点击了上边图片一样-->
        <el-button type="primary" :icon="Plus" size="large" @click="uploadRef.$el.querySelector('input').click()">选择图片</el-button>
        <el-button type="success" :icon="Upload" size="large" @click="onUpdateAvatar">上传头像</el-button>
   </page-container>
   
</template>






<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>